#!/bin/bash
# Copyright 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

usage() {
  echo "usage: $0 [ <board> ]" >&2
  echo "Example:" >&2
  echo "  $0 lumpy" >&2
  exit 1
}

# N.B. The upstart job requires CONFIG_FILE to exist, or it will
# fail.  Although the job will safely handle a file that doesn't
# set BOARD, we require users to create the file with a BOARD
# setting, so as to prevent accidents.

CONFIG_FILE=/etc/default/servod
if [ $# -gt 1 ]; then
  usage
elif [ $# -eq 0 -a ! -f $CONFIG_FILE ]; then
  echo "No board previously configured; you must supply a <board> argument" >&2
  usage
fi

set -e
cd $(dirname $0)/..
sudo true

sudo stop servod || true
sudo make EXTRA_DIRS=beaglebone HOSTOS_STACK_PROTECTOR= install
sudo python setup.py install
sudo python setup.py develop

# The first time we deploy, $CONFIG_FILE won't exist.  After the
# first time, we want to use the existing BOARD setting, if a new
# board isn't given on the command line.
if [ -f $CONFIG_FILE ]; then
  . $CONFIG_FILE
fi
if [ $# -ne 0 ]; then
  BOARD="$1"
fi
CONFIG_TMP=$(mktemp /tmp/hdctools.XXXXXX)
# The string in REVISION will be interpreted by the shell, so we need
# quote special characters.  Quote the string with single-quotes to
# simplify things.
cat <<END >$CONFIG_TMP
BOARD="$BOARD"
REVISION=$(printf %q "$(git log -1 --oneline)")
END
sudo mv $CONFIG_TMP $CONFIG_FILE

sudo start servod
